<template>
  <div class="business-form">
    <el-card>
      <h2>{{ isEdit ? '编辑业务' : '新增业务' }}</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="max-width:500px;">
        <el-form-item label="业务名称" prop="businessName">
          <el-input v-model="form.businessName" />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-input v-model="form.businessType" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option :value="1" label="进行中" />
            <el-option :value="0" label="已结束" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addBusiness, updateBusiness, getBusiness } from '@/api/business'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const isEdit = ref(false)
const form = ref({
  businessName: '',
  businessType: '',
  description: '',
  status: 1
})
const rules = {
  businessName: [{ required: true, message: '请输入业务名称', trigger: 'blur' }]
}

onMounted(async () => {
  if (route.params.id) {
    isEdit.value = true
    const res = await getBusiness(route.params.id)
    Object.assign(form.value, res)
  }
})

const handleSubmit = async () => {
  await formRef.value.validate()
  if (isEdit.value) {
    await updateBusiness(form.value)
    ElMessage.success('修改成功')
  } else {
    await addBusiness(form.value)
    ElMessage.success('新增成功')
  }
  router.push('/business')
}
const goBack = () => router.push('/business')
</script>

<style scoped>
.business-form {
  padding: 32px 0;
}
</style> 